"""
    基于select的并发服务模型
"""

from select import *
from socket import *

#服务端地址
HOST="0.0.0.0"
PORT=1234
ADDR=(HOST,PORT)

#监控列表
rlist=[]
wlist=[]
xlist=[]

def connect_client(sock):
    # 处理客户端连接
    connfd, addr=sock.accept()
    print("Connect from", addr)
    connfd.setblocking(False)
    rlist.append(connfd)  # 增加关注对象

def handle_client(connfd):
    # 处理客户端消息
    data=connfd.recv(1024)
    # 处理客户端退出
    if not data:
        rlist.remove(connfd)  # 不在关注
        connfd.close()
        return
    print(data.decode())
    connfd.send(b'Thanks')


def main():
    # 创建监听套接字
    sock=socket()
    sock.bind(ADDR)
    sock.listen(3)
    # 配合非阻塞IO
    sock.setblocking(False)
    rlist.append(sock)



    # 循环监控关注IO的发生
    while True:
        rs, ws, xs=select(rlist, wlist, xlist)
        for r in rs:
            if r is sock:
                connect_client(r)
            else:
                handle_client(r)


if __name__ == '__main__':
    main()